<template>
  <view class="pay">
    <!-- 1 收货地址 -->
    {{ token }}
    <view class="address u-p-20">
      <view class="address-btn u-flex u-row-center">
        <view v-if="address" class="address-detail">
          <view class="address-detail">{{ detailAddress }}</view>
          <view class="address-user">
            <text>{{ address.userName }}</text>
            <text>{{ address.telNumber }}</text>
          </view>
        </view>

        <u-button
          v-else
          shape="circle"
          type="error"
          plain
          size="medium"
          :custom-style="{ backgroundColor: '#fff!important' }"
          @click="handleChooseAddress"
          >获取收货地址</u-button
        >
      </view>
    </view>

    <u-line color="#eee"></u-line>

    <!-- 2 已选商品 -->
    <view class="goods-list u-p-15">
      <view class="goods-list-title">已选商品</view>
      <view class="goods-list-content">
        <view
          class="cart-item"
          v-for="item in checkedGoodsCart"
          :key="item.goods_id"
        >
          <!-- 2 图片 -->
          <view class="goods-img">
            <u-image
              :src="item.goods_small_logo"
              width="191rpx"
              height="191rpx"
            ></u-image>
          </view>
          <!-- 3 信息 -->
          <view class="goods-info">
            <!-- 名称 -->
            <view class="goods-name u-line-2">{{ item.goods_name }}</view>
            <!-- 价格和数量 -->
            <view class="goods-price-num">
              <view class="goods-price">￥{{ item.goods_price }}</view>
              <view class="goods-num-tool">
                <view class="goods-vnum">X{{ item.num }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 2 统计 -->
    <view class="statistics">
      <view class="all-price">
        合计: <text>￥{{ checkedCartPrice }}</text>
      </view>
      <view class="all-count">
        <u-button type="error" shape="circle" @click="handlePay"
          >去支付({{ checkedCartNums }})</u-button
        >
      </view>
    </view>
  </view>
</template>
  
  <script>
import { mapGetters, mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      address: null, //收货地址
    };
  },
  computed: {
    ...mapGetters("cart", [
      "checkedGoodsCart",
      "checkedCartPrice",
      "checkedCartNums",
    ]),
    ...mapState("user", ["token"]),
    // 详细收货地址信息
    detailAddress() {
      // 判断如果地址为空，就返回一个字符串
      if (!this.address) return "";
      const { provinceName, cityName, countyName, detailInfo } = this.address;
      return provinceName + cityName + countyName + detailInfo;
    },
  },
  methods: {
    ...mapActions("user", ["fetchToken"]),
    // 获取微信地址
    async handleChooseAddress() {
      const [err, res] = await uni.chooseAddress();
      //   console.log(res);
      this.address = res;
    },
    // 去支付
    async handlePay() {
      // 判断有没有token 没有就
      //   调用action来获取token - 设置到vuex中
      if (!this.token) {
        // 获取token
        await this.fetchToken();
      }

      //   执行到这，就一定有token

      // 2 获取用户的信息
      const [err1, res1] = await uni.getUserProfile({
        desc: "用来给用户提供更好的体验",
      });
      //   console.log(res1);

      //   1 调用 wx.login  来获取  code （临时登录凭据 5分钟）
      const [err, { code }] = await uni.login();
      //   console.log(code);

      //#region  1 获取token
      const res3 = await this.$u.post("/users/wxlogin", { ...res1, code });
      //   console.log(res3);
      const { token } = res3.message;
      console.log(121, token);
      //#endregion

      //#region  2 调用创建订单接口
      // 请求头参数要求
      // 请求体参数要求
      const orderParams = {
        order_price: this.checkedCartPrice, //订单总价格
        consignee_addr: this.detailAddress, //收货地址
        goods: this.checkedGoodsCart.map((v) => ({
          goods_id: v.goods_id, //商品id
          goods_number: v.num, //商品数量
          goods_price: v.goods_price, //商品总价格
        })),
      };
      //   调用创建订单接口
      const res4 = await this.$u.post(
        "/my/orders/create",
        orderParams
        //    {Authorization: token}
      );
      console.log(140, res4);
      const { order_number } = res4.message; // 订单编号
      //#endregion

      //#region 3 调用支付接口
      const res5 = await this.$u.post(
        "/my/orders/req_unifiedorder",
        { order_number }
        // {Authorization: token}
      );
      console.log(152, res5);
      //#region 4 调起小程序内 微信支付
      const { pay } = res5.message;
      await uni.requestPayment(pay);

      //   #endregion
      //   #region 5 查询订单的状态
      const res6 = await this.$u.post(
        "/my/orders/chkOrder",
        { order_number }
        // { Authorization: token}
      );
      console.log(res6);

      //#endregion  弹出支付成功
      uni.showToast({
        title: res6.message,
      });

      //#endregion
      // 弹窗显示一会之后 应该跳转到订单页面
      setTimeout(() => {
        console.log("跳转到订单页面");
      }, 1500);
    },
  },
};
</script>
  
  <style lang="scss">
.pay {
  padding-bottom: 111rpx;
}
.cart-item {
  display: flex;
  padding: 10rpx;
  border-bottom: 1rpx solid #ccc;

  .goods-img {
    flex: 2;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .goods-info {
    color: #666;
    flex: 3;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .goods-name {
    }

    .goods-price-num {
      display: flex;
      justify-content: space-between;
      .goods-price {
        color: #eb4450;
      }

      .goods-num-tool {
        width: 140rpx;
        height: 40rpx;

        display: flex;
        justify-content: flex-end;

        .goods-vnum {
        }
      }
    }
  }
}
.statistics {
  position: fixed;
  background-color: #fff;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  border-top: 1rpx solid #ccc;
  display: flex;
  align-items: center;
  padding: 15rpx;
  .all-price {
    flex: 1;
    color: #666;
    text {
    }
  }

  .all-count {
  }
}
</style>